--[[
	获取某邮件的附件，获取，删除这个邮件
]]
local filename = "getmailattach.lua"

local timetool = require "timetool"
local skynet = require "skynet"
local cluster = require "skynet.cluster"
local json = require "cjson.safe"
local queue = require "skynet.queue"
json.encode_sparse_array(true,1,1)

local tostring = tostring

local filelog =require "filelog"
local redisdao = require "redisdao"

local service = nil
local CMD = {
	service = nil
}

local cs = queue()

--
--领取邮件
--
local function getmailattach(rid, msgbody)
    local keyid = tostring(msgbody.keyid)
	local result = cluster.call("datanode", ".router", "select_rk", rid, "rm_mail")
	filelog.print(result[2])

	if result[2][keyid] == nil then
        return {retcode=-8, retstr="mail not exist"} 
    end

    local maildata = result[2][keyid]
	local attach = json.decode(result[2][keyid].attach_json)
	if attach == nil then
        return {retcode = -8, retstr = "no attach"} 
    end

    --看是否有附件
    local is_attach = false
    for k,v in pairs(attach) do
        is_attach = true
        break
    end
	if not is_attach then
        return {retcode = -8, retstr = "no attach"} 
    end

    --领取附件
    local result = cluster.call("datanode", ".router", "delete_rk", rid, "rm_mail", keyid)
    if result[1] ~= 1 then
        return {retcode = -8, retstr = "领取附件失败"} 
    end

    --修改数据
    local total_value = 0 
    for id,value in pairs(attach) do
        local prop_id = tonumber(id)
        value = tonumber(value)
        if value > 0 then
            if id == "fangka" or prop_id == 1 then
                
            elseif id == "diamond" or prop_id == 2 then
                total_value = total_value + value
                service:charge_diamond(value, {mailkeyid = keyid}, "mail")
            elseif id == "coin" or prop_id == 3 then
                service:change_money({coin = value}, {mailkeyid = keyid})
	        elseif prop_id then
                service:charge_prop(prop_id, value, {mailkeyid = keyid}, "mail")
            end
        end
    end   

    --opid 操作id 1发邮件 2删除无附件邮件 3领附件并删除邮件
    local opid = 3

	--保存附件邮件日志 操作名 操作id rid keyid 附件json编码
    local logstr = string.format("%s,%d,%d,%d,%d,%s","del_mail", opid, rid, keyid, maildata.sendrid or 0, json.encode(attach))
    skynet.send(".maillog", "lua", "write", logstr)    
    
    --回调
    if maildata.sendrid == 1 and maildata.sendname ~= "admin" then
        local response = {id = maildata.sendname, result = 1}
        redisdao.query_data(".gmmqredis", "rpush", "responsemq",json.encode(response))
    elseif maildata.sendrid and maildata.sendrid > 99999 then
        --给自己发送通知邮件
        local datefmt = os.date("%m-%d %H:%M:%S")
        local strfmt = "在 %s，你已领取玩家%s（ID：%d）赠送给你的 %d 金币，反馈邮件已发送给对方。（赠送邮件ID：" .. keyid .. "）"
        local content = string.format(strfmt, datefmt, maildata.sendname, maildata.sendrid, math.floor(total_value/100))
        local fields = {subject = "赠送领取通知", content = content}
        skynet.send(".router", "lua", "newmail", rid, fields)
        
        --给赠送方发反馈邮件
        strfmt = "在 %s，你赠送给玩家%s（ID：%d）的 %d 金币，已被对方领取。（赠送邮件ID：" .. keyid .. "）"
        content = string.format(strfmt, datefmt, service.info.rolename, rid, math.floor(total_value/100))
        fields = {subject = "赠送领取通知", content = content}
        skynet.send(".router", "lua", "newmail", maildata.sendrid, fields)
    end

    --红包邮件，增加底钱
    if maildata.mail_type == EMailType.EMAIL_TYPE_HONGBAO then  --红包邮件，算入底钱
        total_value = total_value + (service.money.basemoney or 0)
        local result = cluster.call("datanode", ".router", "update_rk", rid, "rs_money", 0, {basemoney = total_value})
        if result and result[1] == 1 and result[2] then
            service.money.basemoney = total_value
        end
    elseif maildata.mail_type == EMailType.EMAIL_TYPE_REWARD then  --奖励邮件，算入系统奖励
        total_value = total_value + (service.money.system_charge or 0)
        local result = cluster.call("datanode", ".router", "update_rk", rid, "rs_money", 0, {system_charge = total_value})
        if result and result[1] == 1 and result[2] then
            service.money.system_charge = total_value
        end
   end

    return {}  
end

-- socket传来的请求，可以获取邮件列表
function CMD.process(rid, msgbody)
	if not service then
		service = CMD.service
	end
	 
    return cs(getmailattach, rid, msgbody)
end

return CMD
